from django.core.paginator import Paginator
from django.db.models import QuerySet
from django.http import HttpResponse, QueryDict
from django.views import View
import article.models as models
from django.shortcuts import render


class ManageCommentsView(View):
    def get(self, request, id):
        params: QueryDict
        params = request.GET
        user_id = request.session.get('user_id', '')
        article = models.Article.objects.filter(id=id, create_user_id=user_id)
        comments = models.Comments.objects.filter(article_id=id, create_user_id=user_id)
        comments_content = params.get("comments_content", "")
        if comments_content:
            comments = comments.filter(article_id=id, comments_content__contains=comments_content,
                                       create_user_id=user_id)
        page_index = params.get("page_index", "1")
        paginator = Paginator(comments, 5)
        current_page = paginator.page(int(page_index))
        return render(request, 'manage/comments/comments_home.html', locals())


class ManageAddCommentsView(View):
    def get(self, request, id):
        article = models.Article.objects.filter(id=id)
        return render(request, 'manage/comments/comments_add.html', locals())

    def post(self, request, id):
        params: QueryDict
        params = request.POST
        comments_content = params.get("comments_content", "")
        user_id = request.session.get('user_id', '')
        if comments_content:
            models.Comments(article_id=id, create_user_id=user_id, update_user_id=user_id,
                            comments_content=comments_content).save()
            return HttpResponse(f"添加成功，<a href='/manage/comments/{id}'>点击返回评论详情页</a>")
        return HttpResponse(f"添加失败，<a href='/manage/comments/add/{id}'>点击返回重新评论</a>")


class ManageUpdateCommentsView(View):
    def get(self, request, id):
        comments = models.Comments.objects.filter(id=id)
        return render(request, 'manage/comments/comments_update.html', locals())

    def post(self, request, id):
        params: QueryDict
        params = request.POST
        comments_content = params.get("comments_content", "")
        comments = models.Comments.objects.filter(id=id)
        user_id = request.session.get('user_id', '')
        if comments_content:
            comments.filter(id=id).update(comments_content=comments_content, update_user_id=user_id)
            return HttpResponse(f"修改成功，<a href='/manage/comments/{comments[0].article_id}'>点击返回评论详情页</a>")
        return HttpResponse(f"修改失败，<a href='/manage/comments/update/{id}'>点击返回重新修改</a>")


class ManageDelCommentsView(View):
    def get(self, request, id):
        comments = models.Comments.objects.all()
        comments.filter(id=id).delete()
        return HttpResponse(f"删除成功，<a href='/manage/comments/{comments[0].article_id}'>点击返回评论详情页</a>")
